<?php declare(strict_types=1);

$di = \application\units\Di::getInstance();

['where' => $where, 'bindValue' => $bindValue, 'limit' => $limit, 'order' => $order] = $di->businessCommonQuery->build();

$params = [
    'admin_id' => $di->auth->id,
];

$authRoleIds = [];

if ($params['admin_id'] !== null) {
    $roleIds              = $di->auth->getChildrenRoleIds($params['admin_id'], true);
    $where                .= ' and id in (:role_id)';
    $bindValue['role_id'] = $roleIds;
    
    $authRoleIds = $di->auth->getRoleIdsByAdminId($params['admin_id']);
}

$total  = $di->db->find(sprintf('select count(*) total from admin_role where 1=1 %s', $where), $bindValue)['total'];
$rows   = $di->db->query(sprintf('select * from admin_role where 1=1 %s %s %s', $where, $order, $limit), $bindValue);
$ids    = array_column($rows, 'id');
$pids   = array_column($rows, 'pid');
$idDiff = array_diff($pids, $ids);
foreach ($rows as &$row) {
    // 不能操作自己拥有的权限
    if (in_array($row['id'], $authRoleIds)) {
        $row['disabled'] = 1;
    } else {
        $row['disabled'] = 0;
    }
    $row['pid_original'] = $row['pid'];
    if (in_array($row['pid'], $idDiff)) {
        $row['pid'] = 0;
    }
}

return [
    'total' => $total,
    'rows'  => $rows,
];